package site.jlopen.assets.oss;

import java.io.InputStream;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;

public final class OssAutoCloseableClient implements AutoCloseable {

	private OssAutoCloseableClient(AmazonS3 amazonS3Client) {
		this.amazonS3Client = amazonS3Client;
	}

	private AmazonS3 amazonS3Client;

	private static ClientConfiguration clientConfiguration = new ClientConfiguration().withConnectionTimeout(500)
			.withProtocol(Protocol.HTTP).withSocketTimeout(500);

	@Override
	public void close() throws Exception {
		if (amazonS3Client != null) {
			amazonS3Client.shutdown();
		}
	}

	public static OssAutoCloseableClient createClient(AwsOssConfig config) {
		AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
				.withCredentials(new AWSStaticCredentialsProvider(
						new BasicAWSCredentials(config.getAccessKeyId(), config.getSecretAccessKey())))
				.withClientConfiguration(clientConfiguration)
				.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(config.getEndpoint(), ""))
				.withPathStyleAccessEnabled(false).withChunkedEncodingDisabled(true).build();
		return new OssAutoCloseableClient(s3Client);
	}

	public boolean doesBucketExistV2(String bucketName) {
		return amazonS3Client.doesBucketExistV2(bucketName);
	}

	public boolean doesObjectExist(String bucketName, String key) {
		return amazonS3Client.doesObjectExist(bucketName, key);
	}

	public PutObjectResult putObject(
            String bucketName, String fullPath, InputStream input, ObjectMetadata metadata) {
		return amazonS3Client.putObject(bucketName, fullPath, input, metadata);
	}

	public S3Object getObject(String bucketName, String fullPath) {
		return amazonS3Client.getObject(bucketName, fullPath);
	}

	public AmazonS3 getAmazonS3Client() {
		return amazonS3Client;
	}

}
